using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Work.API.Applications.Read.Commands;
using Work.API.Dtos;
using Work.Domain;
using Work.ErrorCode;
using Work.Infrastructure.Interfaces;

namespace Work.API.Applications.Read.CommandHandlers
{
    /// <summary>
    /// 根据预约ID获取病历处理器
    /// </summary>
    public class GetMedicalRecordByAppointmentQueryHandler : IRequestHandler<GetMedicalRecordByAppointmentQuery, ApiResult<MedicalRecordDto?>>
    {
        private readonly IBaseRepository<MedicalRecord> _medicalRecordRepo;
        private readonly IMapper _mapper;

        public GetMedicalRecordByAppointmentQueryHandler(IBaseRepository<MedicalRecord> medicalRecordRepo, IMapper mapper)
        {
            _medicalRecordRepo = medicalRecordRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<MedicalRecordDto?>> Handle(GetMedicalRecordByAppointmentQuery request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<MedicalRecordDto?>();

            try
            {
                var medicalRecord = await _medicalRecordRepo.GetAll()
                    .AsNoTracking()
                    .FirstOrDefaultAsync(m => m.AppointmentId == request.AppointmentId, cancellationToken);

                if (medicalRecord == null)
                {
                    result.Code = ApiEnum.失败;
                    result.Message = "未找到病历";
                    result.Data = null;
                }
                else
                {
                    result.Code = ApiEnum.成功;
                    result.Message = "查询成功";
                    result.Data = _mapper.Map<MedicalRecordDto>(medicalRecord);
                }
            }
            catch (System.Exception ex)
            {
                result.Code = ApiEnum.失败;
                result.Message = $"查询失败：{ex.Message}";
                result.Data = null;
            }

            return result;
        }
    }
}








